<!DOCTYPE html>
<html>
  <head>
    <title>Safe Password Extension Options</title>
    <script type='text/javascript'>
      var defaultOptions = chrome.extension.getBackgroundPage().defaultOptions;

      var messageElement;
      var pswLengthInput;
      var saveButton;
      
      /**
       * Init work.
       */
      function init() {
        var form = document.getElementById('options-form');
        pswLengthInput = form.pswLengthInput;
        saveButton = form.saveButton;
        messageElement = document.getElementById('options-message');
        
        restoreOptions();
      }
    
      /**
       * Saves the current options to local storage.
       */
      function saveOptions() {
        if (validatePswLength()) {
          localStorage['pswLength'] = pswLengthInput.value;
        } else {
          displayMessage('Password length should be an integer between 1 and 20.');
          return;
        }

        markClean();
        displayMessage('Options saved.');
      }

      /**
       * Loads the options from local storage to the page.
       */
      function restoreOptions() {
        var pswLength = localStorage['pswLength'] || defaultOptions.PSW_LENGTH;

        pswLengthInput.value = pswLength;
        markClean();
      }
      
      /**
       * Validates the password length is an integer between 1 and 20.
       */
      function validatePswLength() {        
        var pswLength = pswLengthInput.value;
        if (/^\d+$/.test(pswLength)) {
          var len = parseInt(pswLength);
          return !isNaN(len) && len >= 1 && len <= 20;
        }
        return false;
      }
      
      /**
       * Displays the message.
       */
      function displayMessage(msg) {
        messageElement.innerText = msg;
      }

      function markDirty() {
        saveButton.disabled = false;
      }
      
      function markClean() {
        saveButton.disabled = true;
      }
    </script>
  </head>

  <body onload='init()'>
    <form id='options-form'>
      <div>
        Password length: <input name='pswLengthInput' type='text' oninput='markDirty()'/>
      </div>
      <div>
        <input name='saveButton' type='button' value='Save' onclick='saveOptions()'/>
      </div>
    </form>
    <span id='options-message'></span>
  </body>
</html>
